package com.apes.scm.masterdata.frame.model;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.Name;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.fileserver.File;
import com.apes.scm.masterdata.area.model.Area;
import com.apes.scm.masterdata.area.model.BusinessCircle;
import com.apes.scm.masterdata.area.model.Country;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.model.StockUsage;
import com.apes.scm.masterdata.stock.repository.StockUsageRepository;
import com.apestech.framework.util.StringUtil;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 功能：开店申请
 *
 * @author  LinWZ
 * @create 2019-11-07 16:00
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = BranchEntry.CONST_TABLE_NAME,indexes = {
        @Index(columnList = "code")})
public class BranchEntry extends Model  {
    public static final String CONST_TABLE_NAME = "mas_branch_entry";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "开店申请",prefix="D",padding = 7)
    @Comment("单号")
    private String id;   //单号

    @Column(name = "code", length = 120)
    @Comment("显示编码")
    private String code;  //显示编码

    @Name
    @Column(name = "name", nullable = false, length = 120)
    @Comment("部门名称")
    private String name; //部门名称

//    @OneToOne(mappedBy = "branchEntry", cascade = CascadeType.ALL, orphanRemoval = true)
//    @Comment("门店信息")
//    private Store store;  //门店信息
//Store
//    public Store getStore() {
//        if (store != null) {
//            store.setBranchEntry(this);
//        }
//        return store;
//    }



    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parents_id", referencedColumnName = "id")
    @Comment("上级部门编码")
    private Branch parents;  //上级部门编码

    @Column(name = "levels", nullable = false, length = 120)
    @Comment("级别")
    private int levels; //级别

    @Column(name = "is_last_stage", nullable = false)
    @Comment("末级标记")
    private boolean lastStage = true;  //末级标记


    @Column(name = "ORIGIN", length = 20)
    @Comment("外部ID")
    private String origin; //外部ID

    @Column(name = "valid", nullable = false, columnDefinition = "number(1,0) default 1")
    @Comment("有效")
    private boolean valid = true; //有效

    @Column(name = "auto_Found", nullable = false, columnDefinition = "number(1,0) default 1")
    @Comment("是否自动建群")
    private boolean autoFound = true;   //是否自动建群

    @Name
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "branch_type", referencedColumnName = "id")
    private Enumeration branchType; //部门类型（businessClass）（BC_purchase：采购; BC_sale：销售; BC_other：其他; BC_company: 公司）

    @Transient
    private String path;

    public String getPath() {
        String path = null;
        if (parents != null) path = parents.getPath();
        return path != null ? path + "/" + id : id;
    }


    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof BranchEntry)) return false;
        return (this.getId() == ((BranchEntry) obj).getId());
    }


    @Column(name = "open_day")
    @Comment("开业时间")
    private Date openDay;//开业时间

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    @Comment("所属公司")
    private PartyRole company; //所属公司

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cost_center_id", referencedColumnName = "id")
    @Comment("成本中心")
    private DutyCenter costCenterId;  //成本中心

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "profit_center_id", referencedColumnName = "id")
    @Comment("利润中心")
    private DutyCenter profitCenterId;  //利润中心


    @Column(name = "usage", length = 4000)
    @Comment("库区属性")
    private String usage; //库区属性
    public void setUsage(String usage) {

    }
    @Transient
    private List<StockUsage> usageList;//库区属性;


    @Transient
    private List<Location> locations;//库区;

    @Transient
    private String deptId;

    @Transient
    private String branchId;

    @Transient
    private String depotId;
    
    public List<StockUsage> getUsageList() {
        if (isWrite() || isLoad()) {
            usageList = getReason(this.usage);
        }
        return usageList;
    }
    public void setUsageList(List<StockUsage> usageList) {
        this.usageList = usageList;
        if (!isWrite()) {
            this.usage = toConvertReason(this.usageList);
        }
    }
    @Transient
    private List<StockUsage> getReason(String source) {
        if (StringUtil.isEmpty(source)) return null;
        List<StockUsage> persons = new ArrayList<>();
        String[] rows = source.split(";");
        for (String person : rows) {
            if (person.contains("|")) {
                persons.add(SpringManager.getBean(StockUsageRepository.class).findOne(StringUtils.split(person, "|")[0]));
            }
        }
        return persons;
    }

    private String toConvertReason(List<StockUsage> persons) {
        StringBuffer sb = new StringBuffer();
        for (StockUsage stockUsage : persons) {
            if (sb.length() > 0) {
                sb.append(";");
            }
            sb.append(stockUsage.getId());
            sb.append("|");
            sb.append(stockUsage.getName());  // 格式 id|name;
        }
        return sb.toString();
    }

    @Column(name = "state", length = 16)
    @Comment("状态")
    private String state;   //状态

    @Column(name = "longitude", nullable = false)
    @Comment("经度")
    private double longitude;  //经度

    @Column(name = "latitude", nullable = false)
    @Comment("纬度")
    private double latitude;  //纬度


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "store_Type_Name", referencedColumnName = "id")
    @Comment("门店类型")
    private Enumeration storeType; //门店类型

    @Name
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "store_levels", referencedColumnName = "id")
    private Enumeration storeLevels; //门店等级

//    @Name
//    @ManyToOne(fetch = FetchType.LAZY)
//    @JoinColumn(name = "Business_Circle", referencedColumnName = "id")
//    private Enumeration businessCircle; //商圈

    @Name
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "business_circle_id", referencedColumnName = "id")
    @Comment("商圈")
    private BusinessCircle businessCircle;

    @Column(name = "store_Space", nullable = false, length = 120)
    @Comment("门店面积")
    private Double storeSpace; //门店面积

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "country_id", referencedColumnName = "id")
    @Comment("国家")
    private Country country; //国家

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "province_id", referencedColumnName = "id")
    @Comment("省份")
    private Area province; //省份

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "city_id", referencedColumnName = "id")
    @Comment("城市")
    private Area city; //城市

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "county_id", referencedColumnName = "id")
    @Comment("区县")
    private Area county; //区县

    @Column(name = "address", length = 500)
    @Comment("地址")
    private String address; //地址

    @Column(name = "telephone", length = 500)
    @Comment("联系电话")
    private String telephone; //联系电话

    @Column(name = "boutique_room", length = 500)
    @Comment("精品间面积")
    private String boutiqueRoom; //精品间面积

    @Column(name = "Warehouse", length = 500)
    @Comment("仓库面积")
    private String Warehouse; //仓库面积

    @Column(name = "rental_Area", length = 500)
    @Comment("外租面积")
    private String rentalArea ; //外租面积

    @Column(name = "calculation_Rental", length = 500)
    @Comment("计租面积")
    private String calculationRental; //计租面积

    @Column(name = "receiving_day")
    @Comment("接场日期")
    private Date receivingDay;//接场日期

    @Column(name = "banner_length", length = 20)
    @Comment("横幅长度")
    private String bannerLength; //横幅长度

    @Column(name = "LED_length", length = 20)
    @Comment("led屏长度")
    private String LEDLength; //led屏长度

    @Column(name = "decoration", nullable = false, length = 120)
    @Comment("装修投入")
    private Double decoration; //装修投入【元】

    @Column(name = "equipment", nullable = false, length = 120)
    @Comment("设备投入")
    private Double equipment ; // 设备投入【元】

    @Column(name = "business_day")
    @Comment("营业日期")
    private Date businessDay;

    @Column(name = "business_day_end")
    @Comment("营业日期止")
    private Date businessDayEnd;

    @Column(name = "open_preheat_day")
    @Comment("开业预热")
    private Date openPreheatDay;

    @Column(name = "closing_day")
    @Comment("闭店日期")
    private Date closingDay;

    @OneToMany(mappedBy = "store", cascade=CascadeType.ALL, orphanRemoval = true)
    @Comment("服务工位")
    private List<StationEntry> stations = new ArrayList<>(); //服务工位

    public List<StationEntry> getStations() {
        for (StationEntry station : stations) {
            station.setStore(this);
        }
        return stations;
    }
    public void setStations(List<StationEntry> stations) {
        if (stations == null) stations = new ArrayList<>();
        this.stations.clear();
        this.stations.addAll(stations);
    }

    @File
    @Lob
    @Basic(fetch = FetchType.LAZY)
    @Column(name = "LOGO",columnDefinition = "CLOB")
    @Comment("LOGO")
    private String logo;

}
